package com.cygsunri.util;

import org.assertj.core.util.Preconditions;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;

public class UrlParametersUtil {

    /**
     * 拼接get参数
     *
     * @param baseUrl      baseUrl 例如 https://www.baidu.com/
     * @param parameterMap parameter map
     **/
    public static URI handleUrlParameters(String baseUrl, Map<String, Object> parameterMap) {
        Preconditions.checkArgument(StringUtils.hasText(baseUrl), "Error: url不能为空");
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUrl);

        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        if (!parameterMap.isEmpty()) {
            parameterMap.forEach((key, value) -> {
                if (Objects.nonNull(value)) {
                    params.put(key, Collections.singletonList(String.valueOf(value)));
                }
            });
        }
        return builder.queryParams(params).build().encode().toUri();
    }

}